import * as React from "react";
// import $ from 'jquery';
// import * as nodeAjax from 'ajax-for-node';
require("../stylesheets/ebr.scss");

import DefaultBookDetails, {
  BookDetailsProps as DefaultBookDetailsProps,
} from "opds-web-client/lib/components/BookDetails";
// import DefaultBookDetails, {BookDetailsProps as DefaultBookDetailsProps,} from "../my_modules/opds-web-client/lib/components/BookDetails";// 改为引入改造版

export default class BookDetails extends DefaultBookDetails<
  DefaultBookDetailsProps
> {
  render() {
    // Bookdetail html内容改造，原第三方包class：node_modules/opds-web-client/lib/components/BookDetails.js → BookDetails.prototype.render 部分
    // 尝试过从my_modules/opds-web-client改造后导入，但是失败，会报ActionCreator错误，原因未知

    Object.defineProperty(exports, "__esModule", { value: true });
    const React = require("react");
    const BookCover_1 = require("../my_modules/opds-web-client/lib/components/BookCover");
    const book_1 = require("../my_modules/opds-web-client/lib/utils/book");

    let _a;
    const fields = this.fields();
    const medium = book_1.getMedium(this.props.book);

    getLicensepoolsId(this.props.book); // 获取本书的SImplyE Book id（licensepools_id）

    return React.createElement(
      "div",
      { className: "book-details" },
      React.createElement(
        "div",
        { className: "top", lang: this.props.book.language },
        React.createElement(
          "div",
          { className: "cover" },
          React.createElement(BookCover_1.default, { book: this.props.book })
        ),
        React.createElement(
          "div",
          { className: "details" },
          React.createElement(
            "h1",
            { className: "title" },
            this.props.book.title
          ),
          this.props.book.subtitle &&
            React.createElement(
              "p",
              { className: "subtitle" },
              this.props.book.subtitle
            ),
          this.props.book.series &&
            this.props.book.series.name &&
            React.createElement(
              "p",
              { className: "series" },
              this.props.book.series.name
            ),
          this.props.book.authors &&
            this.props.book.authors.length > 0 &&
            React.createElement(
              "p",
              { className: "authors" },
              "By ",
              this.props.book.authors.join(", ")
            ),

          // 显示书id(simpliyE)
          React.createElement("p", { className: "book-id-p" }, " "),

          this.props.book.contributors &&
            this.props.book.contributors.length > 0 &&
            React.createElement(
              "p",
              { className: "contributors" },
              "Contributors: ",
              this.props.book.contributors.join(", ")
            ),
          React.createElement(
            "ul",
            { className: "fields", lang: "en" },
            fields.map(function (field) {
              return (
                field.value &&
                React.createElement(
                  "li",
                  {
                    className: field.name.toLowerCase().replace(" ", "-"),
                    key: field.name,
                  },
                  field.name,
                  ": ",
                  field.value
                )
              );
            }),
            // medium && (React.createElement("li", { className: "item-icon-container" }, book_1.getMediumSVG(medium)))))),
            medium &&
              React.createElement(
                "li",
                { className: "item-icon-container" },
                book_1.getMediumSVG(medium)
              )
          )
        )
      ),

      React.createElement("div", { className: "divider" }),
      React.createElement(
        "div",
        { className: "main" },
        React.createElement(
          "div",
          { className: "row" },
          React.createElement(
            "div",
            { className: "top col-sm-6 col-sm-offset-3" },
            React.createElement(
              "div",
              { className: "circulation-links" },
              this.circulationLinks()
            ),
            React.createElement(
              "div",
              { className: "circulation-info" },
              this.circulationInfo()
            )
          ),
          React.createElement(
            "div",
            { className: "right-column-links col-sm-3" },
            this.rightColumnLinks()
          )
        ),
        React.createElement("h2", null, "Summary"),
        React.createElement("div", {
          className: "summary",
          lang: this.props.book.language,
          dangerouslySetInnerHTML: {
            __html:
              (_a = this.props.book.summary) !== null && _a !== void 0
                ? _a
                : "",
          },
        })
      )
    );
  }

  fieldNames() {
    return [
      "Published",
      "Issued",
      "Publisher",
      "Audience",
      "Categories",
      "Distributed By",
    ];
  }

  fields() {
    const fields = super.fields();
    const categoriesIndex = fields.findIndex(
      (field) => field.name === "Categories"
    );
    fields[categoriesIndex].value = this.categories();
    // issued 编译错误，暂时去除
    // fields.splice(categoriesIndex, 0, {
    //   name: "Issued",
    //   value: this.props.book.issued,
    // });
    fields.push({
      name: "Audience",
      value: this.audience(),
    });
    fields.push({
      name: "Distributed By",
      value: this.distributor(),
    });
    return fields;
  }

  audience() {
    if (!this.props.book) {
      return null;
    }

    const categories = this.props.book.raw.category;

    if (!categories) {
      return null;
    }

    const audience = categories.find(
      (category) =>
        category["$"]["scheme"] &&
        category["$"]["scheme"]["value"] === "http://schema.org/audience"
    );

    if (!audience) {
      return null;
    }

    let audienceStr = audience["$"]["label"] && audience["$"]["label"]["value"];

    if (["Adult", "Adults Only"].indexOf(audienceStr) !== -1) {
      return audienceStr;
    }

    const targetAge = categories.find(
      (category) =>
        category["$"]["scheme"] &&
        category["$"]["scheme"]["value"] === "http://schema.org/typicalAgeRange"
    );

    if (targetAge) {
      const targetAgeStr =
        targetAge["$"]["label"] && targetAge["$"]["label"]["value"];
      audienceStr += " (age " + targetAgeStr + ")";
    }

    return audienceStr;
  }

  categories() {
    if (!this.props.book) {
      return null;
    }

    const audienceSchemas = [
      "http://schema.org/audience",
      "http://schema.org/typicalAgeRange",
    ];
    const fictionScheme = "http://librarysimplified.org/terms/fiction/";
    const rawCategories = this.props.book.raw.category || [];

    let categories = rawCategories
      .filter(
        (category) =>
          category["$"]["label"] &&
          category["$"]["scheme"] &&
          audienceSchemas
            .concat([fictionScheme])
            .indexOf(category["$"]["scheme"]["value"]) === -1
      )
      .map((category) => category["$"]["label"]["value"]);

    if (!categories.length) {
      categories = rawCategories
        .filter(
          (category) =>
            category["$"]["label"] &&
            category["$"]["scheme"] &&
            category["$"]["scheme"]["value"] === fictionScheme
        )
        .map((category) => category["$"]["label"]["value"]);
    }

    return categories.length > 0 ? categories.join(", ") : null;
  }

  distributor() {
    if (!this.props.book) {
      return null;
    }

    const rawDistributionTags = this.props.book.raw["bibframe:distribution"];
    if (!rawDistributionTags || rawDistributionTags.length < 1) {
      return null;
    }

    const distributor = rawDistributionTags[0]["$"]["bibframe:ProviderName"];
    if (!distributor) {
      return null;
    }

    return distributor.value;
  }
}

// 内部工具方法
const applocation_root =
  localStorage.getItem("MOBEBR_CONFIG_APPLICATION_ROOT") &&
  localStorage.getItem("MOBEBR_CONFIG_APPLICATION_ROOT") !== "/"
    ? localStorage.getItem("MOBEBR_CONFIG_APPLICATION_ROOT")
    : "";
let licensepoolsCache = {};
function getLicensepoolsId(book) {
  // 从OPDS里直接读取失败了，因为涉及到要改一穿第三方包文件，很困难
  // return book.licensepoolsId
  const bookId = book.id;
  if (licensepoolsCache[bookId]) {
    // 从内存获取
    // console.log('licensepoolsId 从内存获取:',licensepoolsCache[bookId])
    setBookId(licensepoolsCache[bookId]);
  } else {
    if (Object.keys(licensepoolsCache).length > 50) {
      licensepoolsCache = {}; // 清空，防止内存溢出
    }
    // 从API获取
    const params = getShortProvidorInfo(bookId);
    let url = applocation_root + "/get_book_id?spid=" + params["spid"];
    if (params["type"]) url += "&type=" + params["type"];
    fetch(url)
      .then(function (res) {
        if (res.ok) {
          return res.json();
        } else {
          return false;
        }
      })
      .then(function (data) {
        if (!data) return false;
        if (data["code"] === "00" && data["licensepools_id"]) {
          setBookId(data["licensepools_id"]);
          licensepoolsCache[bookId] = data["licensepools_id"];
        }
      });
  }
}

function setBookId(bookId) {
  const idDivs = document.getElementsByClassName("book-id-p");
  if (idDivs && idDivs.length > 0) {
    idDivs[0].innerHTML = "Book ID by SimplyE: " + bookId;
  }
}

function getShortProvidorInfo(pid) {
  if (!pid) return false;
  try {
    const pidList = pid.split("/");
    const short_pid = pidList[pidList.length - 1];

    let type = null;
    if (pid.indexOf("Overdrive") !== -1) type = "Overdrive ID";
    else if (pid.indexOf("gutenberg") !== -1) type = "Gutenberg ID";

    return {
      spid: short_pid,
      type: type,
    };
  } catch (e) {
    return false;
  }
}
